package com.jfinal.club._admin.shiti;

import java.util.List;
import com.jfinal.club.common.model.Shiti;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class ShitiAdminService {

	private Shiti dao = new Shiti().dao();
	
	public Page<Shiti> paginate(int pageNum) {
		return dao.paginate(pageNum, 10, "select shiti.id,shiti.question,shiti.answer,banji.clname,exam.ename", "from shiti left join banji on shiti.clid=banji.id left join exam on shiti.exid=exam.id order by shiti.id desc");
	}
	
	public boolean exists(int shitiId, String name) {
		name = name.toLowerCase().trim();
		String sql = "select id from shiti where question = ? and id != ? limit 1";
		Integer id = Db.queryInt(sql, name, shitiId);
		return id != null;
	}
	
	public List<Shiti> getAll() {
		List<Shiti> list = dao.find("select * from shiti order by question");
		return list;
	}
	
	public Ret save(int id, Shiti shiti) {
//		area.setId(id);
		shiti.setQuestion(shiti.getQuestion().trim());
		shiti.save();
		return Ret.ok("msg", "创建成功");
	}
	
	public Shiti edit(int id) {
		return dao.findById(id);
	}
	
	public Ret update(Shiti shiti) {
		if (exists(shiti.getId(), shiti.getQuestion())) {
			return Ret.fail("msg", "试题已经存在");
		}

		shiti.setQuestion(shiti.getQuestion().trim());
		shiti.update();
		return Ret.ok("msg", "修改成功");
	}
	
	public Ret delete(int shitiId) {
		dao.deleteById(shitiId);
		return Ret.ok("msg", "试题删除成功");
	}
}
